<template>
  <div class="group">
    <div>
      <el-select :model-value="provinceId" @change="changeProvince" placeholder="请选择省" clearable>
        <el-option v-for="item in province" :key="item.id" :value="item.id" :label="item.name"></el-option>
      </el-select>
    </div>
    <div>
      <el-select :model-value="shiId" @change="changeShi" placeholder="请选择市" clearable>
        <el-option v-for="item in shi" :key="item.id" :value="item.id" :label="item.name"></el-option>
      </el-select>
    </div>
    <div>
      <el-select :model-value="quId" @change="changeQu" placeholder="请选择区" clearable>
        <el-option v-for="item in qu" :key="item.id" :value="item.id" :label="item.name"></el-option>
      </el-select>
    </div>
  </div>
</template>
<script lang="ts">
import regionTree from "@/utils/regionTree.json";
import { computed, toRefs } from "vue-demi";
export default {
  props: {
    modelValue: {
      type: Array,
      default: () => []
    }
  },
  emits: ["update:modelValue"],
  setup(props, content) {
    const { modelValue } = toRefs(props);

    const provinceId = computed(() => (modelValue.value.length > 0 ? modelValue.value[0] : ""));

    const shiId = computed(() => (modelValue.value.length > 1 ? modelValue.value[1] : ""));
    const quId = computed(() => (modelValue.value.length > 2 ? modelValue.value[2] : ""));
    const province = computed(() => regionTree.map((item) => ({ id: item.id, name: item.name })));
    const shi = computed(() => {
      if (provinceId.value) {
        return regionTree.find((item) => item.id === provinceId.value)!.children;
      } else {
        return [];
      }
    });
    const qu = computed(() => {
      if (shiId.value) {
        return shi.value.find((item) => item.id === shiId.value)!.children;
      } else {
        return [];
      }
    });
    const changeProvince = (v) => {
      content.emit("update:modelValue", [v]);
    };
    const changeShi = (v) => {
      content.emit("update:modelValue", [provinceId.value, v]);
    };
    const changeQu = (v) => {
      content.emit("update:modelValue", [provinceId.value, shiId.value, v]);
    };
    return {
      provinceId,
      shiId,
      quId,
      province,
      shi,
      qu,
      changeProvince,
      changeShi,
      changeQu
    };
  }
};
</script>
<style lang="less" scoped>
.group {
  display: flex;
  & > * {
    flex: 1;
  }
}
</style>
